<?
require_once('./lib/authentication.lib.php');
require_once('./lib/date.lib.php');

if (!$_SESSION["user"]) die("You have to be logged in");

$champ = mysql_escape_string($_POST["champ"]);
$id_to_change = mysql_escape_string($_POST["game"]);
$round = mysql_escape_string($_POST["round"]);
$attendance = mysql_escape_string($_POST["attendance"] );
$date = mysql_escape_string($_POST["date"]);
$stadium = mysql_escape_string($_POST["stadium"]);
$referee = mysql_escape_string($_POST["referee"]);
$home_score = mysql_escape_string($_POST["home_score"]);
$away_score = mysql_escape_string($_POST["away_score"]);
$home_pen = mysql_escape_string($_POST["home_pen"]);
$away_pen = mysql_escape_string($_POST["away_pen"]);
$home_id = mysql_escape_string($_POST["home_id"]);
$away_id = mysql_escape_string($_POST["away_id"]);
$played = mysql_escape_string($_POST["played"]);

?>

<HTML>
<HEAD><TITLE>Edit game</TITLE>
<SCRIPT TYPE="text/javascript" SRC="js/game.js"></SCRIPT>
<SCRIPT TYPE="text/javascript" SRC="js/calendar1.js"></SCRIPT>
</HEAD>

<BODY>

<?
if (isset($_POST["game"]))
{
	if (isset($_POST["round"]) and $round !== "")
	{
		$query = "UPDATE Game SET round = '$round' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	else
	{
		$query = "UPDATE Game SET round = NULL WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["attendance"]) and $attendance !== "")
	{
		$query = "UPDATE Game SET attendance = '$attendance' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	else
	{
		$query = "UPDATE Game SET attendance = NULL WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["date"]) and $date !== "")
	{
		$date = preg_replace("/(\d+)-(\d+)/", "$2/$1", $date);
		$date = preg_replace("/-/", "/", $date);
		echo "$date<BR>";
		$date = convert_date_human_mysql($date);
		echo "$date<BR>";
		$query = "UPDATE Game SET date = '$date' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["stadium"]) and $stadium !== "")
	{
		$query = "UPDATE Game SET stadium = '$stadium' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["referee"]) and $referee !== "")
	{
		$query = "UPDATE Game SET referee = '$referee' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["home_score"]) and $home_score !== "")
	{
		$query = "UPDATE Game SET home_score = '$home_score' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["away_score"]) and $away_score !== "")
	{
		$query = "UPDATE Game SET away_score = '$away_score' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["home_pen"]) and $home_pen !== "")
	{
		$query = "UPDATE Game SET home_pen = '$home_pen' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	else
	{
		$query = "UPDATE Game SET home_pen = NULL WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["away_pen"]) and $away_pen !== "")
	{
		$query = "UPDATE Game SET away_pen = '$away_pen' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	else
	{
		$query = "UPDATE Game SET away_pen = NULL WHERE id = '$id_to_change';";
		mysql_query($query);
	}

	if (isset($_POST["played"]))
	{
		$query = "UPDATE Game SET played = '$played' WHERE id = '$id_to_change';";
		mysql_query($query);
	}
	if (isset($_POST["home_score"]) and isset($_POST["away_score"]))
	{
		$query = "SELECT id FROM Goal WHERE game = '$id_to_change' ORDER BY id;";
		$result = mysql_query($query);
		$goal_ids = array();
		while ($row = mysql_fetch_assoc($result))
		{
			$goal_ids[] = $row["id"];
		}

		while ($home_score + $away_score < count($goal_ids))
		{
			$query = "DELETE FROM Goal where id = '".$goal_ids[0]."';";
			mysql_query($query) or die();
			array_splice($goal_ids, 0, 1);
		}
		
		for ($i = 0; $i < $home_score; ++$i)
		{
			list($player, $team) = split('/', $_POST["home_goal".$i]);
			$min = $_POST["home_min".$i];
			$pen = isset($_POST["home_pen".$i]) ? 1 : 0;
			$own = isset($_POST["home_own".$i]) ? 1 : 0;;
			if (count($goal_ids))
			{
				$query = "UPDATE Goal SET player = '$player', game = '$id_to_change', team = '$team', time = '$min', penalty = '$pen', own_goal = '$own' WHERE id = '".$goal_ids[0]."';";
				array_splice($goal_ids, 0, 1);
			}
			else
			{
				$query = "INSERT INTO Goal (player, game, team, time, penalty, own_goal) VALUES ('$player', '$id_to_change', '$team', '$min', '$pen', '$own');";
			}
			mysql_query($query) or die();
		}

		for ($i = 0; $i < $away_score; ++$i)
		{
			list($player, $team) = split('/', $_POST["away_goal".$i]);
			$min = $_POST["away_min".$i];
			$pen = isset($_POST["away_pen".$i]) ? 1 : 0;
			$own = isset($_POST["away_own".$i]) ? 1 : 0;;
			if (count($goal_ids))
			{
				$query = "UPDATE Goal SET player = '$player', game = '$id_to_change', team = '$team', time = '$min', penalty = '$pen', own_goal = '$own' WHERE id = '".$goal_ids[0]."';";
				array_splice($goal_ids, 0, 1);
			}
			else
			{
				$query = "INSERT INTO Goal (player, game, team, time, penalty, own_goal) VALUES ('$player', '$id_to_change', '$team', '$min', '$pen', '$own');";
			}
			mysql_query($query) or die();
		}
	}
#	echo "<meta http-equiv='refresh' content='0;url=games.php?id=$champ'>";
	echo "<H1>Game updated</H1>";
	?>
	<SCRIPT>
	<!--
	//window.opener.location.reload();
	window.close();
	-->
	</SCRIPT>
	<?
}
else if (isset($_GET["game"]))
{
	$champ = mysql_escape_string($_GET["champ"]);
	$query = "SELECT begin FROM Championship WHERE id = $champ;";
	$result = mysql_query($query);
        $begin = mysql_result($result, 0, "begin");

	$id = mysql_escape_string($_GET["game"]);
	$query = "SELECT * FROM Game LEFT JOIN Team as HomeTeam ON Game.home = HomeTeam.id LEFT JOIN Team as AwayTeam ON Game.away = AwayTeam.id WHERE Game.id = $id;";
	$result = mysql_query($query);

	$home = mysql_result($result, 0, "HomeTeam.name");
	$away = mysql_result($result, 0, "AwayTeam.name");
	$home_id = mysql_result($result, 0, "HomeTeam.id");
	$away_id = mysql_result($result, 0, "AwayTeam.id");
	$round = mysql_result($result, 0, "Game.round");
	$attendance = mysql_result($result, 0, "Game.attendance");
	$home_score = mysql_result($result, 0, "Game.home_score");
	$away_score = mysql_result($result, 0, "Game.away_score");
	$home_pen = mysql_result($result, 0, "Game.home_pen");
	$away_pen = mysql_result($result, 0, "Game.away_pen");
	$date = mysql_result($result, 0, "Game.date");
	$stadium = mysql_result($result, 0, "Game.stadium");
	$referee = mysql_result($result, 0, "Game.referee");
	$played = mysql_result($result, 0, "Game.played");
	$phase = mysql_result($result, 0, "Game.phase");
	
	if (!isset($round))
	{
		$query = "SELECT round FROM Game WHERE phase = '$phase' AND (home = '$home_id' OR away = '$home_id' OR home = '$away_id' OR away = '$away_id') ORDER BY round DESC LIMIT 1;";
		$result_tmp = mysql_query($query);

		if (mysql_numrows($result_tmp))
		{
			$round = mysql_result($result_tmp, 0, "round");
			$round++;
		}
	}

	if (!isset($date) or $date == "0000-00-00 00:00:00")
	{
		$query = "SELECT date FROM Game WHERE phase = '$phase' AND (home = '$home_id' OR away = '$home_id' OR home = '$away_id' OR away = '$away_id') ORDER BY date DESC LIMIT 1;";
		$result_date = mysql_query($query);
		if (mysql_numrows($result_date))
		{
			$date = mysql_result($result_date, 0, "date");
		}
	}

	if (!isset($date) or $date == "0000-00-00 00:00:00")
        {
		$date = $begin;
        }

	$date = convert_date_mysql_human($date);
	
	?>

<FORM ACTION="edit_game.php" METHOD="POST" NAME="main_form">

   <INPUT TYPE="hidden" NAME="game" value="<?echo $id?>">
   <INPUT TYPE="hidden" NAME="champ" value="<?echo $champ?>">
   <P>
   <table id='table_result'><tr>
   <td colspan='4' width='225px'><?echo $home?></td>
   <INPUT TYPE="hidden" NAME="home_id" value="<?echo $home_id?>">
   <td><INPUT TYPE="text" ID="home_score" NAME="home_score" onChange="create_goals(<?echo $champ?>); mark_played();" SIZE="1" value="<?echo $home_score?>"></td>
   <td>x</td>
   <td><INPUT TYPE="text" ID="away_score" NAME="away_score" onChange="create_goals(<?echo $champ?>); mark_played();" SIZE="1" value="<?echo $away_score?>"></td>
   <td colspan='4' width='225px'><?echo $away;?></td>
   <INPUT TYPE="hidden" NAME="away_id" value="<?echo $away_id?>">
   <td style="font-size: 70%">Status:<BR>
   <INPUT TYPE="radio" NAME="played" VALUE="scheduled" <?echo ($played === "scheduled" ? "checked" : "")?>>Scheduled<BR>
   <INPUT TYPE="radio" NAME="played" VALUE="played" <?echo ($played === "played" ? "checked" : "")?>>Played<BR>
   <INPUT TYPE="radio" NAME="played" VALUE="playing" <?echo ($played === "playing" ? "checked" : "")?>>Playing<BR>
   </td></tr></table>

   <div><INPUT TYPE="checkbox" NAME="have_pen" checked onClick='getElement("table_pens").style.display = this.checked ? "block" : "none"; document.main_form.home_pen.value = ""; document.main_form.away_pen.value = ""'>Penalties?</div>
   <table id='table_pens'><tr>
   <td width='225px'></td>
   <td><INPUT TYPE="text" NAME="home_pen" SIZE="1" value="<?echo $home_pen?>"></td>
   <td>x</td>
   <td><INPUT TYPE="text" NAME="away_pen" SIZE="1" value="<?echo $away_pen?>"></td>
   <td width='225px'></td>
   </tr>
   </table>
   <?
   if (!isset($home_pen) and !isset($away_pen))
   {
   ?>
	<SCRIPT TYPE="text/javascript">
	<!--
	document.main_form.have_pen.checked = false;
	getElement("table_pens").style.display = "none";
	-->
	</SCRIPT>
   <?
   }
   ?>
   <P>Round:
   <INPUT TYPE="text" NAME="round" SIZE="1" value="<?echo $round?>">
   <P>Attendance:
   <INPUT TYPE="text" NAME="attendance" value="<?echo $attendance?>">
   <P>Date:
   <INPUT TYPE="text" NAME="date" value="<?echo $date?>">
   <A HREF="javascript:cal1.popup();"><img src="img/cal/cal.gif" width="16" height="16" border="0" alt="Click Here to Pick up the date"></a>
   <P>Stadium:
   <SELECT NAME="stadium" onChange="new_stadium(<?echo $champ?>, this);">
   <OPTION value="0">--- Not set ---</OPTION>
<?
$query = "SELECT * FROM Stadium ORDER BY name;";
$result_stadium = mysql_query($query);

$num_stadium = mysql_numrows($result_stadium);
if ($num_stadium == 0)
{
	die("No stadiums found");
}

$i = 0;
while ($i < $num_stadium)
{
	$id_stadium = mysql_result($result_stadium, $i, "id");
	$name_stadium = mysql_result($result_stadium, $i, "name");

	if ($id_stadium == $stadium)
	{
		echo "<OPTION selected value='$id_stadium'>$name_stadium</OPTION>\n";
	}
	else
	{
		echo "<OPTION value='$id_stadium'>$name_stadium</OPTION>\n";
	}

	$i++;
}
?>
   <OPTION value="0">--- New stadium ---</OPTION>
   </SELECT>
   <P>Referee
   <SELECT NAME="referee" onChange="new_referee(<?echo $champ?>, this);">
   <OPTION value="0">--- Not set ---</OPTION>
<?
$query = "SELECT * FROM Referee, referee_champ WHERE Referee.id = referee_champ.referee AND referee_champ.champ = $champ ORDER BY name;";
$result_referee = mysql_query($query);

$num_referee = mysql_numrows($result_referee);

$i = 0;
while ($i < $num_referee)
{
	$id_referee = mysql_result($result_referee, $i, "id");
	$name_referee = mysql_result($result_referee, $i, "name");
	$referee_location = mysql_result($result_referee, $i, "location");

	if ($id_referee == $referee)
	{
		echo "<OPTION selected value='$id_referee'>$name_referee" . ($referee_location ? " ($referee_location)" : "") . "</OPTION>\n";
	}
	else
	{
		echo "<OPTION value='$id_referee'>$name_referee" . ($referee_location ? " ($referee_location)" : "") . "</OPTION>\n";
	}

	$i++;
}
?>
   <OPTION value="0">--- New referee ---</OPTION>
   </SELECT>
   <P><INPUT TYPE="submit" NAME="submit" value="Send">
</FORM>

<SCRIPT TYPE="text/javascript">
<!--
var cal1 = new calendar1(document.forms['main_form'].elements['date']);
cal1.year_scroll = true;
cal1.time_comp = true;
-->
</SCRIPT>

<SCRIPT TYPE="text/javascript">
<!--
<?

echo "HomeId = $home_id;\n";
echo "HomeName = '" . str_replace("'", "\\'", $home) . "';\n";
echo "AwayId = $away_id;\n";
echo "AwayName = '" . str_replace("'", "\\'", $away) . "';\n";

$query = "SELECT * FROM Player, team_player WHERE Player.id = team_player.player AND team_player.team = '$home_id' AND team_player.champ = '$champ' ORDER BY Player.name;";
$result_players = mysql_query($query);

$num_players = mysql_numrows($result_players);
echo "HomePlayers = new Array($num_players);\n";
echo "HomeGoals = new Array($num_players);\n";
$i = 0;
while ($i < $num_players)
{
	$player_name = mysql_result($result_players, $i, "Player.name");
	$player_id = mysql_result($result_players, $i, "Player.id");

	$player_name = preg_replace("/'/", "\\'", $player_name);
	
	echo "HomePlayers[$i] = new Array(3);\n";
	echo "HomePlayers[$i][0] = '$player_name';\n";
	echo "HomePlayers[$i][1] = '$player_id';\n";
	echo "HomePlayers[$i][2] = '$home_id';\n";
	
	$i++;
}

$query = "SELECT * FROM Player, team_player WHERE Player.id = team_player.player AND team_player.team = '$away_id' AND team_player.champ = '$champ' ORDER BY Player.name;";
$result_players = mysql_query($query);

$num_players = mysql_numrows($result_players);
echo "AwayPlayers = new Array($num_players);\n";
echo "AwayGoals = new Array($num_players);\n";
$i = 0;
while ($i < $num_players)
{
	$player_name = mysql_result($result_players, $i, "Player.name");
	$player_id = mysql_result($result_players, $i, "Player.id");

	$player_name = preg_replace("/'/", "\\'", $player_name);

	echo "AwayPlayers[$i] = new Array(3);\n";
	echo "AwayPlayers[$i][0] = '$player_name';\n";
	echo "AwayPlayers[$i][1] = '$player_id';\n";
	echo "AwayPlayers[$i][2] = '$away_id';\n";
	
	$i++;
}

$query = "SELECT player, team, time, penalty, own_goal FROM Goal WHERE game = '$id' ORDER BY Goal.time;";
$result_goals = mysql_query($query);

$num_goals = mysql_numrows($result_goals);
$i = 0;
$count_home = 0;
$count_away = 0;
while ($i < $num_goals)
{
	$goal_player = mysql_result($result_goals, $i, "player");
	$goal_team = mysql_result($result_goals, $i, "team");
	$goal_time = mysql_result($result_goals, $i, "time");
	$goal_pen = mysql_result($result_goals, $i, "penalty");
	$goal_own = mysql_result($result_goals, $i, "own_goal");

	if ($goal_team == $home_id and $goal_own == 0 or $goal_team == $away_id and $goal_own == 1)
	{
		echo "HomeGoals[$count_home] = new Array(5);\n";
		echo "HomeGoals[$count_home][0] = '$goal_player';\n";
		echo "HomeGoals[$count_home][1] = '$goal_time';\n";
		echo "HomeGoals[$count_home][2] = '$goal_pen';\n";
		echo "HomeGoals[$count_home][3] = '$goal_own';\n";
		echo "HomeGoals[$count_home][4] = '$goal_team';\n";
		$count_home++;
	}
	else
	{
		echo "AwayGoals[$count_away] = new Array(5);\n";
		echo "AwayGoals[$count_away][0] = '$goal_player';\n";
		echo "AwayGoals[$count_away][1] = '$goal_time';\n";
		echo "AwayGoals[$count_away][2] = '$goal_pen';\n";
		echo "AwayGoals[$count_away][3] = '$goal_own';\n";
		echo "AwayGoals[$count_away][4] = '$goal_team';\n";
		$count_away++;
	}
	
	$i++;
}
?>

create_goals(<?echo $champ?>);
-->
</SCRIPT>

<?
}
?>


</BODY>
</HTML>
